package com.kapo.egroup.config;

import com.kapo.egroup.filter.JwtAuthenticationTokenFilter;
import com.kapo.egroup.security.handler.AuthenticationEntryPointHandler;
import com.kapo.egroup.security.handler.CustomerAccessDeniedHandler;
import com.kapo.egroup.security.handler.LoginFailureHandler;
import com.kapo.egroup.security.handler.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;

/**
 * @Title SecurityConfig
 * @Description TODO
 * @Author 86159
 * @Date 2022-10-16 03:04
 **/
@EnableWebSecurity
@Configuration
public class SecurityConfig {
    /**
     * 自定义用户认证逻辑
     * 原生为在内存中查找用户信息
     * 自定义为在数据库中查找数据库信息
     * 重写了loadUserByUsername方法
     */
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 登录认证成功处理器
     */
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    /**
     * 用户认证失败处理器
     */
    @Autowired
    private LoginFailureHandler loginFailureHandler;

    /**
     * 自定义授权过程中的异常
     */
    @Autowired
    private CustomerAccessDeniedHandler accessDeniedHandler;

    /**
     * 自定义认证异常类
     */
    @Autowired
    private AuthenticationEntryPointHandler authenticationEntryPointHandler;

    /**
     * token认证过滤器
     * 用于确定登录状态
     * 获取request header中的token
     * 并通过token获取用户信息，再获取用户权限
     */
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{
        return httpSecurity.formLogin()
                .loginProcessingUrl("/api/user/login")//设置登录api
                .successHandler(loginSuccessHandler)//登录成功
                .failureHandler(loginFailureHandler)//登录失败
                .and().cors().configurationSource(corsConfiguration())
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)//关闭Session
                .and()
                .authorizeRequests()//允许部分api匿名访问
                .antMatchers("/api/user/login").anonymous()
                .antMatchers("/api/user/register").anonymous()
                .antMatchers("/api/user/checkusername/*").anonymous()
                .antMatchers("/api/config/**").anonymous()
                .antMatchers(
                        "/swagger-ui.html",
                        "/swagger-ui/*",
                        "/swagger-resources/**",
                        "/v2/api-docs",
                        "/webjars/**",
                        "/configuration/ui",
                        "/configuration/security",
                        "/resource/**"
                ).anonymous()
                .anyRequest().authenticated()
                .and().exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPointHandler)
                .accessDeniedHandler(accessDeniedHandler)
                .and().cors()
                .and().userDetailsService(userDetailsService)
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    /**
     * 获取AuthenticationManager（认证管理器），登录时认证使用
     * @param authenticationConfiguration
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /**
     * 加密操作
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return bCryptPasswordEncoder();
    }

    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /**
     * Cors 的配置信息 配置+路径
     */
    CorsConfigurationSource corsConfiguration (){
        // Cors配置类
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true); // 是否返回时生成凭证
        corsConfiguration.setAllowedHeaders(Arrays.asList("*")); // 允许请求携带哪些请求头信息
        corsConfiguration.setAllowedMethods(Arrays.asList("*")); // 允许哪些类型的请求方法
        corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:8081","http://43.139.139.213:8081")); // 允许哪些域可以进行方法
        corsConfiguration.setMaxAge(3600L); // 设置预检的最大的时长
        corsConfiguration.setExposedHeaders(Collections.emptyList()); // 设置返回暴露的响应头信息

        // 设置注册URL 配置类
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource() ;
        source.registerCorsConfiguration("/**",corsConfiguration);

        return source;
    }

}
